package com.example.proxy.model;

import com.example.proxy.anno.RestCompont;
import com.example.proxy.anno.RestSend;
import com.example.proxy.http.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

public class RestFactoryBean<T> implements FactoryBean<T> {
    private final Logger log = LoggerFactory.getLogger(this.getClass());


    private Class<?> objType;

    public RestFactoryBean(Class<?> objType) {
        this.objType = objType;
    }

    @Override
    public T getObject() throws Exception {
        long start = System.currentTimeMillis();
        Object proxyInstance = Proxy.newProxyInstance(objType.getClassLoader(),
                new Class[]{objType}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        RestCompont clzAnnotation = objType.getAnnotation(RestCompont.class);
                        RestSend mehAnnotation = method.getAnnotation(RestSend.class);
                        String url = clzAnnotation.value() +"/"+ mehAnnotation.value();
                        String res;
                        if (args == null||args.length==0) {
                            res = WebClient.doGet(url);
                        }else {
                            Map<String, String> arg = (Map<String, String>) args[0];
                            res = WebClient.doGet(url, arg);
                        }
                        return res;
                    }
                });
        log.info("生成代理类：{}",objType.getName());
        return (T) proxyInstance;
    }

    @Override
    public Class<?> getObjectType() {
        return this.objType;
    }
}
